# Gunicorn 配置文件

# 绑定的 IP 和端口 TODO
bind = "0.0.0.0:8089"

# 工作进程数
workers = 6

# 工作模式
worker_class = "uvicorn.workers.UvicornWorker"

# 超时设置（秒）
timeout = 600

# 允许请求排队的最大数量
backlog = 2048

# 调试模式
debug = False

# 重载
reload = False

# 日志级别
loglevel = "info"

# 访问日志格式
access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"'

# 错误日志文件 - 按天分割
errorlog = "-"

# 访问日志文件 - 按天分割
accesslog = "-"

# 进程名称
proc_name = "gunicorn_app"

# 优雅地重启工作进程
graceful_timeout = 120

# 保持连接
keepalive = 60

# 最大请求数
max_requests = 1000
max_requests_jitter = 50

# 预加载应用
preload_app = True

# 守护进程模式
daemon = False

# 用户和组
# user = "nobody"
# group = "nogroup"

# SSL 配置（如果需要）
# keyfile = "/path/to/keyfile"
# certfile = "/path/to/certfile"

# 统计信息
# statsd_host = "localhost:8125"
# statsd_prefix = "gunicorn"

import logging
import logging.handlers
import os
from datetime import datetime

# 确保日志目录存在
log_dir = "../logs"
if not os.path.exists(log_dir):
    os.makedirs(log_dir)

# 创建日志处理器
class DailyRotatingHandler(logging.Handler):
    def __init__(self, base_path):
        super().__init__()
        self.base_path = base_path
        self.current_date = None
        self.current_file = None

    def emit(self, record):
        try:
            current_date = datetime.now().strftime('%Y-%m-%d')
            if self.current_date != current_date:
                self.current_date = current_date
                if self.current_file:
                    self.current_file.close()
                filename = f"{self.base_path}_{current_date}.log"
                self.current_file = open(filename, 'a', encoding='utf-8')
            
            msg = self.format(record)
            self.current_file.write(msg + '\n')
            self.current_file.flush()
        except Exception:
            self.handleError(record)

# 配置错误日志
error_logger = logging.getLogger('gunicorn.error')
error_handler = DailyRotatingHandler(os.path.join(log_dir, 'error'))
error_formatter = logging.Formatter('%(asctime)s [%(process)d] [%(levelname)s] %(message)s')
error_handler.setFormatter(error_formatter)
error_logger.addHandler(error_handler)

# 配置访问日志
access_logger = logging.getLogger('gunicorn.access')
access_handler = DailyRotatingHandler(os.path.join(log_dir, 'access'))
access_formatter = logging.Formatter('%(message)s')
access_handler.setFormatter(access_formatter)
access_logger.addHandler(access_handler)
